/*
#          .,:,,,                                        .::,,,::.          
#        .::::,,;;,                                  .,;;:,,....:i:         
#        :i,.::::,;i:.      ....,,:::::::::,....   .;i:,.  ......;i.        
#        :;..:::;::::i;,,:::;:,,,,,,,,,,..,.,,:::iri:. .,:irsr:,.;i.        
#        ;;..,::::;;;;ri,,,.                    ..,,:;s1s1ssrr;,.;r,        
#        :;. ,::;ii;:,     . ...................     .;iirri;;;,,;i,        
#        ,i. .;ri:.   ... ............................  .,,:;:,,,;i:        
#        :s,.;r:... ....................................... .::;::s;        
#        ,1r::. .............,,,.,,:,,........................,;iir;        
#        ,s;...........     ..::.,;:,,.          ...............,;1s        
#       :i,..,.              .,:,,::,.          .......... .......;1,       
#      ir,....:rrssr;:,       ,,.,::.     .r5S9989398G95hr;. ....,.:s,      
#     ;r,..,s9855513XHAG3i   .,,,,,,,.  ,S931,.,,.;s;s&BHHA8s.,..,..:r:     
#    :r;..rGGh,  :SAG;;G@BS:.,,,,,,,,,.r83:      hHH1sXMBHHHM3..,,,,.ir.    
#   ,si,.1GS,   sBMAAX&MBMB5,,,,,,:,,.:&8       3@HXHBMBHBBH#X,.,,,,,,rr    
#   ;1:,,SH:   .A@&&B#&8H#BS,,,,,,,,,.,5XS,     3@MHABM&59M#As..,,,,:,is,   
#  .rr,,,;9&1   hBHHBB&8AMGr,,,,,,,,,,,:h&&9s;   r9&BMHBHMB9:  . .,,,,;ri.  
#  :1:....:5&XSi;r8BMBHHA9r:,......,,,,:ii19GG88899XHHH&GSr.      ...,:rs.  
#  ;s.     .:sS8G8GG889hi.        ....,,:;:,.:irssrriii:,.        ...,,i1,  
#  ;1,         ..,....,,isssi;,        .,,.                      ....,.i1,  
#  ;h:               i9HHBMBBHAX9:         .                     ...,,,rs,  
#  ,1i..            :A#MBBBBMHB #  .r1,..        ,..;3BMBBBHBB#Bh.     ..                    ....,,,,,i1;   
#   :h;..       .,..;,1XBMMMMBXs,.,, .. :: ,.               ....,,,,,,ss.   
#    ih: ..    .;;;, ;;:s58A3i,..    ,. ,.:,,.             ...,,,,,:,s1,    
#    .s1,....   .,;sh,  ,iSAXs;.    ,.  ,,.i85            ...,,,,,,:i1;     
#     .rh: ...     rXG9XBBM#M#MHAX3hss13&&HHXr         .....,,,,,,,ih;      
#      .s5: .....    i598X&&A&AAAAAA&XG851r:       ........,,,,:,,sh;       
#      . ihr, ...  .         ..                    ........,,,,,;11:.       
#         ,s1i. ...  ..,,,..,,,.,,.,,.,..       ........,,.,,.;s5i.         
#          .:s1r,......................       ..............;shs,           
#          . .:shr:.  ....                 ..............,ishs.             
#              .,issr;,... ...........................,is1s;.               
#                 .,is1si;:,....................,:;ir1sr;,                  
#                    ..:isssssrrii;::::::;;iirsssssr;:..                    
#                         .,::iiirsssssssssrri;;:.
*/
package com.itheima.health.config;

import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * <dl>
 * <dd>描述: ~ CustomerUserDetail</dd>
 * <dd>创建时间：  10:58 2021/3/6</dd>
 * <dd>创建人： guodong</dd>
 * <dt>版本历史: </dt>
 * <pre>
 * Date         Author         Version     Description
 * ------------------------------------------------------------------
 * 2021/3/6      guodong         1.0        1.0 Version
 * </pre>
 * </dl>
 */
@Component
public class CustomerUserDetail implements UserDetailsService {

    private static Map<String, User> userDd = new HashMap<>();

    /**
     * @Author: guodong
     * @Date: 11:00 2021/3/6
     * @ClassName: CustomerUserDetail
     * @Parms
     * @ReturnType:
     * @Description: 初始化用户角色信息-模拟数据库
    */
    static {
        //1.初始化权限
        Permission addPerms = new Permission("添加权限", "add");
        Permission findPerms = new Permission("查询权限", "find");
        Permission updatePerms = new Permission("修改权限", "update");
        Permission delPerms = new Permission("删除权限", "del");
        //2.初始化角色
        Role adminRole = new Role("超级管理员", "ROLE_ADMIN");
        adminRole.getPermissions().add(addPerms);
        adminRole.getPermissions().add(findPerms);
        adminRole.getPermissions().add(updatePerms);
        adminRole.getPermissions().add(delPerms);

        //如果没有以ROLE_开头会自动追加
        Role role1 = new Role("角色1", "ROLE_01");
        role1.getPermissions().add(addPerms);
        role1.getPermissions().add(findPerms);

        /*BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        bCryptPasswordEncoder.encode("1234")*/
        Role role2 = new Role("角色2", "ROLE_02");
        role2.getPermissions().add(findPerms);
        //3.初始化用户
        User adminUser = new User();
        adminUser.setUsername("admin");
        adminUser.setPassword("{bcrypt}$2a$10$5HAxR3B3zpaPCh5xUAhLq.sFeq9gRnrIx6AZBWLn9y/OXMEWK3AKC");
        adminUser.getRoles().add(adminRole);

        userDd.put(adminUser.getUsername(), adminUser);

        User sanUser = new User();
        sanUser.setUsername("zhangsan");
        sanUser.setPassword("{bcrypt}$2a$10$5HAxR3B3zpaPCh5xUAhLq.sFeq9gRnrIx6AZBWLn9y/OXMEWK3AKC");
        sanUser.getRoles().add(role1);

        userDd.put(sanUser.getUsername(), sanUser);

        User lisiUser = new User();
        lisiUser.setUsername("lisi");
        lisiUser.setPassword("{noop}1234");
        lisiUser.getRoles().add(role2);

        userDd.put(lisiUser.getUsername(), lisiUser);
    }



    /**
     * @Author: guodong
     * @Date: 10:59 2021/3/6
     * @ClassName: CustomerUserDetail
     * @Parms [username]
     * @ReturnType: org.springframework.security.core.userdetails.UserDetails
     * @Description: 加载用户权限相关信息
    */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userDd.get(username);
        if(user == null){
            return null;
        }
        //1.获取角色
        StringBuffer authStr = new StringBuffer();
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            authStr.append(role.getKeyword());
            authStr.append(",");
            //2.获取权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                authStr.append(permission.getKeyword());
                authStr.append(",");
            }
        }
        if(authStr.length()>0){
            authStr.deleteCharAt(authStr.length()-1);
        }
        //3.创建security中的user返回
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(authStr.toString()));
    }
}
